package com.feature50.makeover;

import javax.swing.*;
import java.util.*;

public class FavoritesListModel extends AbstractListModel {
    private List<ENode> favorites = new ArrayList<ENode>();
    private Set<ENode> favoritesSet = new HashSet<ENode>();
    private static final Comparator favoriteComparator = new Comparator() {
        public int compare(Object o1, Object o2) {
            ENode n1 = (ENode) o1;
            ENode n2 = (ENode) o2;
            return n1.getDisplay().compareTo(n2.getDisplay());
        }
    };

    public FavoritesListModel() {}

    public FavoritesListModel(List<ENode> favorites) {
        favorites.addAll(favorites);
    }

    public void addFavorites(ENode... favorites) {
        List<ENode> temp = new ArrayList<ENode>();
        for (int i = 0; i < favorites.length; i++) {
            boolean result = favoritesSet.add(favorites[i]);
            if (result) temp.add(favorites[i]);
        }

        if (!temp.isEmpty()) {
            this.favorites.addAll(temp);
            resort();
        }
    }

    private void resort() {
        Collections.sort(favorites, favoriteComparator);
        fireContentsChanged(this, 0, getSize() - 1);
    }

    public void addFavorite(ENode favorite) {
        boolean added = favoritesSet.add(favorite);
        if (added) {
            favorites.add(favorite);
            resort();
        }
    }

    public void removeFavorite(ENode favorite) {
        boolean removed = favoritesSet.remove(favorite);
        if (removed) {
            favorites.remove(favorite);
            resort();
        }
    }

    public Object getElementAt(int index) {
        return favorites.get(index);
    }

    public int getSize() {
        return favorites.size();
    }

    public boolean isFavorite(ENode node) {
        return favoritesSet.contains(node);
    }
}